# -*- coding: utf-8 -*-
import orjson
from fastapi import APIRouter, Depends, HTTPException, Path
from fastapi.responses import JSONResponse, Response
from database import get_db
from sqlalchemy.orm import Session
from app.yg_crm import schemas, crud, orm
from typing import List, Optional
from utility.utility import result, RespResult, json_result_reps
from fastapi_utils.api_model import APIMessage, APIModel

test_router = APIRouter()

description1 = """
使用自己写的json化函数，
有自动null值处理 
"""


@test_router.get("/get_users_test_myjson", description=description1)
def get_users_test(db: Session = Depends(get_db)):
    users: List[orm.User] = crud.get_users(db)
    # print(users)
    if not users:
        raise HTTPException(status_code=404, detail="users do not exists")
    # print(users)
    return json_result_reps(data=users)


description2 = """
使用基础类Response，直接处理json返回
"""


@test_router.get("/test_response_json", description=description2)
async def test():
    user = {"name": "John Doe吴", "email": "john.doe@example.com"}
    json_bytes = orjson.dumps(user)
    return Response(
        content=json_bytes,
        media_type="application/json; charset=UTF-8",
        headers={
            'Accept-Charset': 'utf-8'
        }
    )


description3 = """
用转pydantic的方法，处理返回间接含有orm数据结果的情况；但会经受验证
"""


@test_router.get("/get_users_to_pydantic", response_model=RespResult, response_model_exclude_unset=True, response_model_exclude_none=True, description=description3)
def get_users_test(db: Session = Depends(get_db)):
    users: List[orm.User] = crud.get_users(db)
    if not users:
        raise HTTPException(status_code=404, detail="users do not exists")

    return result(data=users, schema=schemas.User)


@test_router.get("/get_users_test", summary="orm结果json化测试")
def get_users_test(db: Session = Depends(get_db)):
    """
    直接返回纯orm对象，fastapi response 能够自动解析;\n
    需要print来触发数据加载
    """
    users: List[orm.User] = crud.get_users(db)
    if not users:
        raise HTTPException(status_code=404, detail="users do not exists")
    print(users)
    # db.refresh(users) #不管用，对于数据显示问题; refresh或flush的作用，commit包括
    return users


# * 处理有默认值，和没默认值情况同时在，函数层的魔术语法。
# 函数参数的规则是：positional param不能在 named param之后；named param只能是其它named param
@test_router.get("/items/{item_id}")
async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results


@test_router.get("/tpl_type/create_init_data")
async def set_template_type(db: Session = Depends(get_db)):
    t1 = schemas.TemplateType(code="EC-waybill", name="电商单据样式模板", category='oss', create_by="admin", update_by="admin")
    t2 = schemas.TemplateType(code="Finance-checkbill", name="财务对帐单导出模板", category='json', create_by="admin", update_by="admin")
    res = crud.create_template_type(db, [t1, t2])
    # return result(res, schema=schemas.TemplateType)
    return json_result_reps(data=res)


@test_router.get("/tpl_type/all")
async def set_template_type(db: Session = Depends(get_db)):
    return crud.get_template_types(db)


